package ru.urfc.portal.developer_tasks.ejb_tests;

import java.util.List;

import org.slf4j.LoggerFactory;

import ru.urfc.portal.dao.filter.Filter;
import ru.urfc.portal.developer_tasks.BaseTestEjb;
import ru.urfc.portal.model.Branch;
import ru.urfc.portal.model.accounting.Contragent;
import ru.urfc.portal.model.documents.Document;

public class BasePersistenceTestEjb extends BaseTestEjb {
	
	public void testFindExactlyOne() {
		Contragent client = persist(new Contragent("qq"));
		Contragent foundClient = exactlyOne(find(Branch.SVERD, Contragent.class, "name", "qq"));
		assertEquals(client.getId(), foundClient.getId());
	}
	
	public void testFindExactlyOneFailedCauseNone() {
		try {
			exactlyOne(find(Branch.SVERD, Contragent.class, "name", "qq"));
			fail("Expected exception: client with name qq should not exist");
		} catch (Exception e) {
			// ok
		}
	}
	
	public void testFindExactlyOneFailedCauseMany() {
		try {
			persist(new Contragent("qq"));
			persist(new Contragent("qq"));
			exactlyOne(find(Branch.SVERD, Contragent.class, "name", "qq"));
			fail("Expected exception: should exist 2 clients with name qq");
		} catch (Exception e) {
			// ok
		}
	}

	public void testFindOneOrNullFoundNull() {
		assertEquals(null, oneOrNull(find(Branch.SVERD, Contragent.class, "name", "qq")));
	}

	public void testFindOneOrNullFoundone() {
		Contragent client = persist(new Contragent("qq"));
		Contragent foundClient = oneOrNull(find(Branch.SVERD, Contragent.class, "name", "qq"));
		assertEquals(client.getId(), foundClient.getId());		
	}

	public void testFindOneOrNullFailed() {
		try {
			persist(new Contragent("qq"));
			persist(new Contragent("qq"));
			oneOrNull(find(Branch.SVERD, Contragent.class, "name", "qq"));
			fail("Expected exception: should exist 2 clients with name qq");
		} catch (Exception e) {
			// ok
		}
	}

	public void testFilterWithFetch() {
		List<Document> documents = find(Document.class, new Filter("client.id", 1L));
		assertEquals(true, documents.size() > 0);
		Document document = documents.get(0);
		Long docId = document.getId();
		detach(document);
		detach(document.getClient());
		
		LoggerFactory.getLogger(getClass()).debug("begin");
		Document document2 = exactlyOne(find(Document.class, new Filter("id", docId)));
		detach(document2);
		//TODO 
//		assertNull(document2.getClient());
	}
	
}
